package com.thinkgem.jeesite.modules.bu.web;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.bu.entity.BuOrder;
import com.thinkgem.jeesite.modules.bu.entity.BuOrderCp;
import com.thinkgem.jeesite.modules.bu.entity.BuSalesman;
import com.thinkgem.jeesite.modules.bu.service.BuOrderCpService;
import com.thinkgem.jeesite.modules.bu.service.BuOrderService;
import com.thinkgem.jeesite.modules.bu.service.BuSalesmanService;
import com.thinkgem.jeesite.modules.bu.service.IBuCustomerService;
import com.thinkgem.jeesite.modules.bu.service.IBuSupplierService;
import com.thinkgem.jeesite.modules.bu.utils.DateUtil;
import com.thinkgem.jeesite.modules.bu.utils.ExcelTest;
import com.thinkgem.jeesite.modules.bu.utils.OrderStateEnum;
import com.thinkgem.jeesite.modules.cms.entity.Site;
import com.thinkgem.jeesite.modules.sys.entity.Office;
import com.thinkgem.jeesite.modules.sys.entity.Role;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.IUserService;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;

/**
 * 内部订单Controller
 * 
 * @author ThinkGem
 * @version 2018-08-26
 */
@Controller
@RequestMapping(value = "${adminPath}/bu/buInternalOrder")
public class BuInternalOrderController extends BaseController {

	@Autowired
	private BuOrderService buOrderService;

	@Resource
	private IBuSupplierService buSupplierService;

	@Resource
	private IBuCustomerService buCustomerService;

	@Resource
	private BuOrderCpService buOrderCpService;

	@Resource
	private IUserService userService;
	
	@Resource
	private BuSalesmanService buSalesmanService;
	
	@Value("${httpPriffix}")
	private String httpPriffix;

	@ModelAttribute
	public BuOrder get(@RequestParam(required = false) String id) {
		BuOrder entity = null;
		if (StringUtils.isNotBlank(id)) {
			BuOrder order = new BuOrder();
			order.setId(id);
			order.setDelFlag("0");
			entity = buOrderService.get(order);
		}
		if (entity == null) {
			entity = new BuOrder();
		}
		return entity;
	}

	/**
	 * flag (0:审核;1:修改;2:查看;3:新增;4:复制)
	 * @param buOrder
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("bu:buInternalOrder:view")
	@RequestMapping(value = { "list", "" })
	public String list(BuOrder buOrder, HttpServletRequest request, HttpServletResponse response, Model model) {

		Page<BuOrder> page = null;
		List<String> orderStateList = constructOrderState();
		buOrder.setOrderStateList(orderStateList);
		page = buOrderService.findPage(new Page<BuOrder>(request, response), buOrder);
		model.addAttribute("httpPriffix", httpPriffix);
		model.addAttribute("page", page);

		return "modules/bu/buInternalOrderList";
	}

	private List<String> constructOrderState() {
		List<String> orderStateList = new ArrayList<>();
		orderStateList.add(String.valueOf(OrderStateEnum.C1000.getCode()));
		orderStateList.add(String.valueOf(OrderStateEnum.C1001.getCode()));
		orderStateList.add(String.valueOf(OrderStateEnum.C1002.getCode()));
		orderStateList.add(String.valueOf(OrderStateEnum.C1003.getCode()));
		orderStateList.add(String.valueOf(OrderStateEnum.C1004.getCode()));
		orderStateList.add(String.valueOf(OrderStateEnum.C1005.getCode()));
		orderStateList.add(String.valueOf(OrderStateEnum.C1006.getCode()));
		return orderStateList;
	}

	
	@RequiresPermissions("bu:buInternalOrder:operate:delivery")
	@RequestMapping(value = "selectById")
	public String selectById(BuOrder buOrder, HttpServletRequest request, HttpServletResponse response, Model model) {
		String id = request.getParameter("id");
		String flag = request.getParameter("flag");
		String write = request.getParameter("write");
		String orderState = request.getParameter("orderState");
		model.addAttribute("id", id);
		model.addAttribute("flag", flag);
		model.addAttribute("write", write);
		model.addAttribute("orderState", orderState);
		return "modules/bu/buInternalOrderDelivery";
	}
	
	@RequiresPermissions("bu:buInternalOrder:operate:toUpdate")
	@RequestMapping(value = "toUpdate")
	public String toUpdate(HttpServletRequest request, HttpServletResponse response, BuOrder buOrder, Model model) {

		String flag = request.getParameter("flag") == null ? "" : request.getParameter("flag");
		String write = request.getParameter("write");
		
		String customerId = buOrder.getCustomerId();
		BuSalesman salesman = new BuSalesman();
		salesman.setCustomerId(customerId);
		List<BuSalesman> entityList = buSalesmanService.findList(salesman);
		
		model.addAttribute("entityList", entityList);
		model.addAttribute("flag", flag);
		model.addAttribute("write", write);
		return "modules/bu/buInternalOrderEdit";

	}
	
	@RequiresPermissions("bu:buInternalOrder:view")
	@RequestMapping(value = "form")
	public String form(HttpServletRequest request, HttpServletResponse response, BuOrder buOrder, Model model) {

		String flag = request.getParameter("flag") == null ? "" : request.getParameter("flag");
		String write = request.getParameter("write");
		
		User user = UserUtils.getUser();
		buOrder.setCreateBy(user);
		String orderNo = DateUtil.getDate();
		buOrder.setOrderNo(orderNo);
		
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		buOrder.setOrderDate(format.format(new Date()));
		buOrder.setCreateUser(user.getName());
		
		BuSalesman salesman = new BuSalesman();
		salesman.setCustomerId(user.getId());
		List<BuSalesman> entityList = buSalesmanService.findList(salesman);
		model.addAttribute("entityList", entityList);
		model.addAttribute("flag", flag);
		model.addAttribute("write", write);
		return "modules/bu/buInternalOrderForm";

	}
	
	@RequiresPermissions("bu:buInternalOrder:view")
	@RequestMapping(value = "view")
	public String view(HttpServletRequest request, HttpServletResponse response, BuOrder buOrder, Model model) {
		
		String flag = request.getParameter("flag") == null ? "": request.getParameter("flag");
		String write = request.getParameter("write");
		
		String salesManId = buOrder.getSalesmanId();
		BuSalesman salesMan = new BuSalesman();
		salesMan.setId(salesManId);
		salesMan.setDelFlag("0");
		
		List<BuSalesman> entityList = new ArrayList<>();
		BuSalesman entity = buSalesmanService.get(salesMan);
		entityList.add(entity);
		
		model.addAttribute("entityList", entityList);
		model.addAttribute("buOrder", buOrder);
		model.addAttribute("flag", flag);
		model.addAttribute("write", write);
		return "modules/bu/buInternalOrderView";
	
	}
	
	@RequiresPermissions("bu:buInternalOrder:operate:edit")
	@RequestMapping(value = "save")
	public String save(HttpServletRequest request, HttpServletResponse response, BuOrder buOrder, Model model,
			RedirectAttributes redirectAttributes) {
		
		if (!beanValidator(model, buOrder)) {
			return form(request, response, buOrder, model);
		}
		String flag = request.getParameter("flag");
		String write = request.getParameter("write");
		buOrder.setOrderState("1001");
        User user = UserUtils.getUser();
        
        Office office = user.getOffice();
        buOrder.setOffice(office);
        String siteId = Site.getCurrentSiteId();
        Site site = new Site();
        site.setId(siteId);
        buOrder.setSite(site);
        if(buOrder.getPicUrl().contains("dev_desk")){
        	String[] bb = buOrder.getPicUrl().split("dev_desk");
    		System.out.println(bb[0] + "        " + bb[1]);
    		buOrder.setPicUrl(bb[1]);
        }
        
		BuSalesman salesMan = buSalesmanService.get(buOrder.getSalesmanId());
		
		buOrder.setSalesManName(salesMan.getSalesmanName());
        
        buOrder.setCreateBy(user);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        buOrder.setOrderDate(format.format(new Date()));
        buOrder.setDelFlag("0");
        buOrder.setOrderType("0");
		buOrderService.save(buOrder);
		
		model.addAttribute("flag", flag);
		model.addAttribute("write", write);
		addMessage(redirectAttributes, "保存成功");
		return "redirect:" + Global.getAdminPath() + "/bu/buInternalOrder/?repage";
		
	}

	@RequiresPermissions("bu:buInternalOrder:operate:update")
	@RequestMapping(value = "updateDelivery")
	public String updateDelivery(HttpServletRequest request, HttpServletResponse response, BuOrder buOrder, Model model,
			RedirectAttributes redirectAttributes) {

		String flag = request.getParameter("flag");
		String write = request.getParameter("write");
		String id = request.getParameter("id");
		User user = UserUtils.getUser();

		if (!beanValidator(model, buOrder)) {
			return form(request, response, buOrder, model);
		}
		if(buOrder.getOrderState() == "1000"){
			buOrder.setOrderState("1001");
		}else if(buOrder.getOrderState() == "1001"){
			buOrder.setOrderState("1002");
		}else if(buOrder.getOrderState() == "1002"){
			buOrder.setOrderState("1003");
		}else if(buOrder.getOrderState() == "1003"){
			buOrder.setOrderState("1004");
		}else if(buOrder.getOrderState() == "1004"){
			buOrder.setOrderState("1005");
		}else if(buOrder.getOrderState() == "1005"){
			buOrder.setOrderDate("1006");
		}
		
		buOrder.setId(id);
		buOrder.setUpdateBy(user);
		buOrder.setUpdateDate(new Date());
		buOrderService.updateDelivery(buOrder);
		
		model.addAttribute("flag", flag);
		model.addAttribute("write", write);
		addMessage(redirectAttributes, "保存成功");
		return "redirect:" + Global.getAdminPath() + "/bu/buInternalOrder/?repage";
		
	}

	protected BuOrderCp constructBuOrderCpEntity(BuOrder buOrder) {

		BuOrderCp orderCp = new BuOrderCp();

		orderCp.setOrderNo(buOrder.getOrderNo());
		orderCp.setProductNo(buOrder.getProductNo());
		orderCp.setOrderDate(buOrder.getOrderDate());
		orderCp.setShipDate(buOrder.getShipDate());
		orderCp.setProductName(buOrder.getProductName());

		orderCp.setCrafts(buOrder.getCrafts());
		orderCp.setElectroplate(buOrder.getElectroplate());
		orderCp.setBack(buOrder.getBack());
		orderCp.setPackages(buOrder.getPackages());
		orderCp.setFitting(buOrder.getFitting());

		orderCp.setPicUrl(buOrder.getPicUrl());
		orderCp.setQuantity(buOrder.getQuantity());
		orderCp.setSalesPrice(buOrder.getSalesPrice());
		orderCp.setSalesModelFee(buOrder.getSalesModelFee());
		orderCp.setProduceFee(buOrder.getProduceFee());

		orderCp.setProduceModelFee(buOrder.getProduceModelFee());
		orderCp.setSalesTotalFee(buOrder.getSalesTotalFee());
		orderCp.setProduceTotalFee(buOrder.getProduceTotalFee());

		return orderCp;

	}

	@RequiresPermissions("bu:buInternalOrder:operate:delete")
	@RequestMapping(value = "delete")
	public String delete(BuOrder buOrder, RedirectAttributes redirectAttributes) {
		buOrderService.delete(buOrder);
		addMessage(redirectAttributes, "删除成功");
		return "redirect:" + Global.getAdminPath() + "/bu/buInternalOrder/?repage";
	}

	@RequiresPermissions("bu:buInternalOrder:operate:copy")
	@RequestMapping(value = "copy")
	public String copy(HttpServletRequest request, BuOrder buOrder, Model model) {

		String flag = request.getParameter("flag");
		String write = request.getParameter("write");
		
		User user = UserUtils.getUser();
		
		Role customerRole = new Role();
		User customerUser = new User();
		customerRole.setId("6"); // 业务员
		customerUser.setRole(customerRole);
		customerUser.setDelFlag("0");

		User supplierUser = new User();
		Role supplierRole = new Role();
		supplierRole.setId("7952384aba3e401aa0b4cc713d5b71b1"); // 厂商
		supplierRole.setDelFlag("0");
		supplierUser.setRole(supplierRole);

		List<User> supplierList = userService.findRef(supplierUser);
		List<User> customerList = userService.findRef(customerUser);

		model.addAttribute("supplierList", supplierList);
		model.addAttribute("customerList", customerList);
		
		BuSalesman salesman = new BuSalesman();
		salesman.setCustomerId(user.getId());
		List<BuSalesman> entityList = buSalesmanService.findList(salesman);
		model.addAttribute("entityList", entityList);
		
		model.addAttribute("buOrder", buOrder);
		buOrder.setId("");
		buOrder.setOrderNo(DateUtil.getDate());
		model.addAttribute("flag", flag);
		model.addAttribute("write", write);
		return "modules/bu/buInternalOrderForm";
	}

	/**
	 * 查询订单状态
	 * 
	 * @return
	 */
	@RequestMapping(value = "orderStatus")
	@ResponseBody
	public Map<String, Object> getOrderStatus(HttpServletRequest request) {

		Map<String, Object> map = new HashMap<>();

		// 订单状态(0:待审核;1:待生产;2:生产中;3:生产完成;4:待发货;5:待收货;6:待收款;7:已完成)
		int externalPendingReview = 0; // 外部待审核订单状态
		int externalToBeProduced = 0; // 外部待审核订单状态
		int externalInProduction = 0; // 外部生产中订单状态
		int externalToBeDelivered = 0; // 外部待发货订单状态
		int externalPendingReceipt = 0; // 外部待收货订单状态
		int externalPendingPayment = 0; // 外部待收款订单状态
		int externalCompleted = 0; // 外部已完成订单状态

		int internalPendingReview = 0; // 内部待审核订单状态
		int internalToBeProduced = 0; // 内部待审核订单状态
		int internalInProduction = 0; // 内部生产中订单状态
		int internalProductionIsCompleted = 0; // 内部生产完成订单状态
		int internalToBeDelivered = 0; // 内部待发货订单状态
		int internalPendingReceipt = 0; // 内部待收货订单状态
		int internalPendingPayment = 0; // 内部待收款订单状态
		int internalCompleted = 0; // 内部已完成订单状态

		boolean trueFlag = true;
		boolean falseFlag = false;

		int internalOrderType = 0;
		int externalOrderType = 1;

		if (trueFlag == true) {

			BuOrder internalPendingReviewOrder = new BuOrder();
			internalPendingReviewOrder.setOrderState("1000");
			internalPendingReviewOrder.setOrderType(String.valueOf(internalOrderType));
			internalPendingReview = buOrderService.selectOrderStatus(internalPendingReviewOrder);
			map.put("internalPendingReview", internalPendingReview);

			BuOrder internalToBeProducedOrder = new BuOrder();
			internalToBeProducedOrder.setOrderState("1001");
			internalToBeProducedOrder.setOrderType(String.valueOf(internalOrderType));
			internalToBeProduced = buOrderService.selectOrderStatus(internalToBeProducedOrder);
			map.put("internalToBeProduced", internalToBeProduced);

			BuOrder internalInProductionOrder = new BuOrder();
			internalInProductionOrder.setOrderState("1002");
			internalInProductionOrder.setOrderType(String.valueOf(internalOrderType));
			internalInProduction = buOrderService.selectOrderStatus(internalInProductionOrder);
			map.put("internalInProduction", internalInProduction);

			BuOrder internalProductionIsCompletedOrder = new BuOrder();
			internalProductionIsCompletedOrder.setOrderState("1003");
			internalProductionIsCompletedOrder.setOrderType(String.valueOf(internalOrderType));
			internalProductionIsCompleted = buOrderService.selectOrderStatus(internalProductionIsCompletedOrder);
			map.put("internalProductionIsCompleted", internalProductionIsCompleted);

			BuOrder internalToBeDeliveredOrder = new BuOrder();
			internalToBeDeliveredOrder.setOrderState("1004");
			internalToBeDeliveredOrder.setOrderType(String.valueOf(internalOrderType));
			internalToBeDelivered = buOrderService.selectOrderStatus(internalToBeDeliveredOrder);
			map.put("internalToBeDelivered", internalToBeDelivered);

			BuOrder internalPendingReceiptOrder = new BuOrder();
			internalPendingReceiptOrder.setOrderState("1005");
			internalPendingReceiptOrder.setOrderType(String.valueOf(internalOrderType));
			internalPendingReceipt = buOrderService.selectOrderStatus(internalPendingReceiptOrder);
			map.put("internalPendingReceipt", internalPendingReceipt);

			BuOrder internalPendingPaymentOrder = new BuOrder();
			internalPendingPaymentOrder.setOrderState("1006");
			internalPendingPaymentOrder.setOrderType(String.valueOf(internalOrderType));
			internalPendingPayment = buOrderService.selectOrderStatus(internalPendingPaymentOrder);
			map.put("internalPendingPayment", internalPendingPayment);

			BuOrder internalCompletedOrder = new BuOrder();
			internalCompletedOrder.setOrderState("1006");
			internalCompletedOrder.setOrderType(String.valueOf(internalOrderType));
			internalCompleted = buOrderService.selectOrderStatus(internalCompletedOrder);
			map.put("internalCompleted", internalCompleted);

		}
		if (falseFlag == false) {
			BuOrder externalPendingReviewOrder = new BuOrder();
			externalPendingReviewOrder.setOrderState("1000");
			externalPendingReviewOrder.setOrderType(String.valueOf(externalOrderType));
			externalPendingReview = buOrderService.selectOrderStatus(externalPendingReviewOrder);
			map.put("externalPendingReview", externalPendingReview);

			BuOrder externalToBeProducedOrder = new BuOrder();
			externalToBeProducedOrder.setOrderState("1001");
			externalToBeProducedOrder.setOrderType(String.valueOf(externalOrderType));
			externalToBeProduced = buOrderService.selectOrderStatus(externalToBeProducedOrder);
			map.put("externalToBeProduced", externalToBeProduced);

			BuOrder externalInProductionOrder = new BuOrder();
			externalInProductionOrder.setOrderState("1002");
			externalInProductionOrder.setOrderType(String.valueOf(externalOrderType));
			externalInProduction = buOrderService.selectOrderStatus(externalInProductionOrder);
			map.put("externalInProduction", externalInProduction);

			BuOrder externalToBeDeliveredOrder = new BuOrder();
			externalToBeDeliveredOrder.setOrderState("1003");
			externalToBeDeliveredOrder.setOrderType(String.valueOf(externalOrderType));
			externalToBeDelivered = buOrderService.selectOrderStatus(externalToBeDeliveredOrder);
			map.put("externalToBeDelivered", externalToBeDelivered);

			BuOrder externalPendingReceiptOrder = new BuOrder();
			externalPendingReceiptOrder.setOrderState("1005");
			externalPendingReceiptOrder.setOrderType(String.valueOf(externalOrderType));
			externalPendingReceipt = buOrderService.selectOrderStatus(externalPendingReceiptOrder);
			map.put("externalPendingReceipt", externalPendingReceipt);

			BuOrder externalPendingPaymentOrder = new BuOrder();
			externalPendingPaymentOrder.setOrderState("1005");
			externalPendingPaymentOrder.setOrderType(String.valueOf(externalOrderType));
			externalPendingPayment = buOrderService.selectOrderStatus(externalPendingPaymentOrder);
			map.put("externalPendingPayment", externalPendingPayment);

			BuOrder externalCompletedOrder = new BuOrder();
			externalCompletedOrder.setOrderState("1006");
			externalCompletedOrder.setOrderType(String.valueOf(externalOrderType));
			externalCompleted = buOrderService.selectOrderStatus(externalCompletedOrder);
			map.put("externalCompleted", externalCompleted);

		}
		return map;
	}
	
	/**
	 * @param request
	 * @param buOrder
	 * @param model
	 * @return
	 */
	@RequiresPermissions("bu:buInternalOrder:operate:ios0")
	@RequestMapping(value = "ios0")
	public void ios0(HttpServletRequest request, BuOrder buOrder, Model model) {
		
	}
	
	/**
	 * @param request
	 * @param buOrder
	 * @param model
	 * @return
	 */
	@RequiresPermissions("bu:buInternalOrder:operate:ios1")
	@RequestMapping(value = "ios1")
	public void ios1(HttpServletRequest request, BuOrder buOrder, Model model) {
		
	}
	
	/**
	 * @param request
	 * @param buOrder
	 * @param model
	 * @return
	 */
	@RequiresPermissions("bu:buInternalOrder:operate:ios2")
	@RequestMapping(value = "ios2")
	public void ios2(HttpServletRequest request, BuOrder buOrder, Model model) {
		
	}
	
	/**
	 * @param request
	 * @param buOrder
	 * @param model
	 * @return
	 */
	@RequiresPermissions("bu:buInternalOrder:operate:ios3")
	@RequestMapping(value = "ios3")
	public void ios3(HttpServletRequest request, BuOrder buOrder, Model model) {
		
	}
	
	/**
	 * @param request
	 * @param buOrder
	 * @param model
	 * @return
	 */
	@RequiresPermissions("bu:buInternalOrder:operate:ios4")
	@RequestMapping(value = "ios4")
	public void ios4(HttpServletRequest request, BuOrder buOrder, Model model) {
		
	}
	
	/**
	 * @param request
	 * @param buOrder
	 * @param model
	 * @return
	 */
	@RequiresPermissions("bu:buInternalOrder:operate:ios5")
	@RequestMapping(value = "ios5")
	public void ios5(HttpServletRequest request, BuOrder buOrder, Model model) {
		
	}
	
	/**
	 * @param request
	 * @param buOrder
	 * @param model
	 * @return
	 */
	@RequiresPermissions("bu:buInternalOrder:operate:ios6")
	@RequestMapping(value = "ios6")
	public void ios6(HttpServletRequest request, BuOrder buOrder, Model model) {
		
	}
	
	@Value("${win.userfiles.basedir}")
	private String winUserfilesBasedir;
	
	@Value("${linux.userfiles.basedir}")
	private String linuxUserfilesBasedir;
	
	/**
	 * 下载生产单
	 * @param buOrder
	 * @param request
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("bu:buInternalOrder:operate:export")
    @RequestMapping(value = "exportProductFile", method=RequestMethod.GET)
    public String exportProductFile(BuOrder buOrder, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            ExcelTest.reportOrderMergeXls(buOrder, "xx", "yy",response,httpPriffix,winUserfilesBasedir,linuxUserfilesBasedir);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出订单失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/bu/buInternalOrder/list?repage";
    }
	
}
